package com.scorcher.ilink;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.scorcher.ilink.ListXmlParser.Entry;

public class FileBrowser extends ListActivity {

	// debugging
	public final static boolean D = true;
	public final static String TAG = "FileBrowser";

	// List of Files
	private List<Entry> files;
	private List<String> dates;

	// File Types
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (D)
			Log.e(TAG, "+++ ON CREATE +++");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loading_screen);
		new XmlParseTask().execute("/iLink/list.xml");
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		String fileName = files.get(position).name;
		Uri fileUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),fileName));
		Intent fileIntent = new Intent(Intent.ACTION_VIEW);
		String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
	    String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
	    fileIntent.setDataAndType(fileUri, mimetype);
		PackageManager packageManager = getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(fileIntent, 0);
		boolean isIntentSafe = activities.size() > 0;
		if(isIntentSafe)
			startActivity(fileIntent);
	}

	private class XmlParseTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... files) {
			try {
				return loadXmlFile(files[0]);
			} catch (XmlPullParserException e) {
				if (D)
					Log.e(TAG, "Xml Pull Exception");
				return getResources().getString(R.string.xml_pull_exception);
			} catch (IOException e) {
				if (D)
					Log.e(TAG, "Connection Error");
				return getResources().getString(R.string.connection_error);
			}
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			setContentView(R.layout.file_browser_tab);
			displayFiles();
		}

	}

	/**
	 * 
	 * Class to modify the displaying of files on the screen
	 * 
	 */
	@SuppressWarnings("hiding")
	private class FileDisplayAdaptor<Entry> extends ArrayAdapter<Entry> {

		private int mResource;
		private List<Entry> mObjects = null;
		private int mFieldId;
		private LayoutInflater mInflater;

		public FileDisplayAdaptor(Context context, int resource,
				int textViewResourceId, List<Entry> objects) {
			super(context, resource, textViewResourceId, objects);
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mFieldId = textViewResourceId;
			mObjects = objects;
			mResource = resource;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return createViewFromResource(position, convertView, parent,
					mResource);
		}

		private View createViewFromResource(int position, View convertView,
				ViewGroup parent, int resource) {
			View view;
			TextView text;
			ImageView icon;
			TextView size;
			TextView date;
			if (convertView == null) {
				view = mInflater.inflate(resource, parent, false);
			} else {
				view = convertView;
			}

			try {
				if (mFieldId == 0) {
					// If no custom field is assigned, assume the whole resource
					// is a TextView
					text = (TextView) view;
				} else {
					// Otherwise, find the TextView field within the layout
					text = (TextView) view.findViewById(mFieldId);
				}
				icon = (ImageView) view.findViewById(R.id.icon);
				size = (TextView) view.findViewById(R.id.size);
				date = (TextView) view.findViewById(R.id.date);
			} catch (ClassCastException e) {
				Log.e("ArrayAdapter",
						"You must supply a resource ID for a TextView");
				throw new IllegalStateException(
						"ArrayAdapter requires the resource ID to be a TextView",
						e);
			}

			Entry item = getItem(position);
			String[] details = item.toString().split(",");
			icon.setImageResource(iconFinder(details[0]));
			double sizeInt = Double.parseDouble(details[1]) / (1024 * 1024);
			if(details[0].length()>40)
			{
				details[0]=details[0].substring(0,37)+"...";
			}
			text.setText(details[0]);
			if(sizeInt<1.00)
			{
				sizeInt=sizeInt*1024;
				size.setText("" + new BigDecimal(sizeInt).setScale(2,RoundingMode.HALF_UP) + " KB");
			}
			else
			size.setText("" + new BigDecimal(sizeInt).setScale(2,RoundingMode.HALF_UP) + " MB");
			date.setText(details[2]);
			return view;
		}

		@Override
		public Entry getItem(int position) {
			return mObjects.get(position);
		}

	}

	private int iconFinder(String file) {
		String fileName = file.toLowerCase();
		if (fileName.endsWith(".txt") | fileName.endsWith(".xml") | fileName.endsWith(".java") | fileName.endsWith(".c")) {
			return R.drawable.text_file;
		} else if ((fileName.endsWith(".jpg")) | (fileName.endsWith(".jpeg"))
				| (fileName.endsWith(".bmp")) | (fileName.endsWith(".png")) | (fileName.endsWith(".gif"))) {
			return R.drawable.image_file;
		}
		else if ((fileName.endsWith(".doc")) | (fileName.endsWith(".docx"))
				| (fileName.endsWith(".rtf")))
			return R.drawable.doc_file;
		else if(fileName.endsWith(".apk"))
			return R.drawable.android_file;
		else if(fileName.endsWith(".pdf"))
			return R.drawable.pdf_file;
		else if((fileName.endsWith(".rar"))|(fileName.endsWith(".zip"))|(fileName.endsWith(".tar.bz")))
			return R.drawable.compressed_file;
		else if((fileName.endsWith(".mp3"))|(fileName.endsWith(".wav"))|(fileName.endsWith(".mp4")))
			return R.drawable.music_file;
		else
			return R.drawable.unknown_file;
	}

	private void displayFiles() {
		if (D) Log.e(TAG, "Here1");
		dates = new ArrayList<String>();
		if (D) Log.e(TAG, "Here2");
		if(files!=null)
		for (Entry e : files) {
			if (D) Log.e(TAG, "Here3 "+e.name);
			dates.add(e.date);
		}
		if (D) Log.e(TAG, "Here4");
		ArrayAdapter<Entry> fileList = new FileDisplayAdaptor<Entry>(this,
				R.layout.file_list_row, R.id.text1, files);
		if (D) Log.e(TAG, "Here5");
		setListAdapter(fileList);
	}

	private String loadXmlFile(String file) throws XmlPullParserException,
			IOException {
		File list = new File(Environment.getExternalStorageDirectory(), file);
		ListXmlParser listXmlParser = new ListXmlParser();
		files = listXmlParser.parse(new FileInputStream(list));
		return "File Reading Complete";
	}
}
